package com.health.platform.common.http;

import com.alibaba.fastjson.JSONObject;
import org.apache.http.client.config.RequestConfig;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.util.EntityUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.io.IOException;
import java.nio.charset.Charset;
import java.util.Map;

/**
 * <p>json返回值转换器配置</p>
 * <p>创建日期：2018-02-01</p>
 *
 * @author 杨洲 yangzhou@neusoft.com
 */
public class HttpClientUtils {

    private static final Logger logger = LoggerFactory.getLogger(HttpClientUtils.class);

    /**
     * 编码格式。发送编码格式统一用UTF-8
     */
    private static final String ENCODING = "UTF-8";

    public static HttpClientResult httpPostRequest(String url, Map<String, String> param) {
        try {
            // 创建httpClient实例
            CloseableHttpClient httpClient = HttpClients.createDefault();
            // 创建httpPost远程连接实例
            HttpPost httpPost = new HttpPost(url);
            // 配置请求参数实例 设置连接主机服务超时时间
            RequestConfig requestConfig = RequestConfig.custom().setConnectTimeout(10000)
                    // 设置连接请求超时时间
                    .setConnectionRequestTimeout(10000)
                    // 设置读取数据连接超时时间
                    .setSocketTimeout(30000)
                    .build();
            // 为httpPost实例设置配置
            httpPost.setConfig(requestConfig);
            // 设置请求头
            httpPost.addHeader("content-type", "application/json;charset=utf-8");
            httpPost.setEntity(new StringEntity(JSONObject.toJSONString(param), Charset.forName("UTF-8")));
            // httpClient对象执行post请求,并返回响应参数对象
            CloseableHttpResponse closeableHttpResponse = httpClient.execute(httpPost);
            // 从响应对象中获取响应内容
            return new HttpClientResult(closeableHttpResponse.getStatusLine().getStatusCode(), EntityUtils.toString(closeableHttpResponse.getEntity(), ENCODING));
        } catch (IOException e) {
            logger.error("http", e);
        }
        return null;
    }

}
